package com.whz.clear;

import lombok.extern.slf4j.Slf4j;
import java.lang.ref.Cleaner;
/**
 * @Author: sinosoft
 * @Description: 保证房间在回收之前必须进行清洁
 * @Date: Create in 14:17 2021/4/30
 * @Modified By:
 */
@Slf4j
public class Room implements AutoCloseable {
    private static final Cleaner clear = Cleaner.create();

    /**
     * 保存清除房间所需的资源
     */
    private static class State implements Runnable {
        /*房间内垃圾堆数量*/
        int numJunkPiles;

        public State(int numJunkPiles) {
            this.numJunkPiles = numJunkPiles;
        }

        @Override
        public void run() {
            log.info("开始打扫垃圾");
            log.info("垃圾清洁完毕");
            numJunkPiles = 0;
        }
    }
    /*房间的状态*/
    private final State state;
    /*在合适的时候清理房间*/
    private final Cleaner.Cleanable cleanable;

    public Room(int numJunkPiles) {
        state = new State(numJunkPiles);
        cleanable = clear.register(this, state);
    }

    @Override
    public void close() throws Exception {
        cleanable.clean();
    }

    @Override
    public String toString() {
        return "房间内垃圾堆的数量: " + state.numJunkPiles;
    }
}
